package com.xtjc03.serial.domain;

import gnu.io.SerialPort;
import lombok.Data;
import org.apache.mina.transport.serial.SerialAddress;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.InvalidParameterException;

@Component
@ConfigurationProperties(prefix = "com")
@Data
public class ComProperties {

    private String name;

    private int bauds;

    private int dataBits;

    private int stopBits;

    private int parity;

    private int flowControl;

    private String listener;

    public SerialAddress.DataBits getDataBits() {
        switch (dataBits){
            case SerialPort.DATABITS_5:
                return SerialAddress.DataBits.DATABITS_5;
            case SerialPort.DATABITS_6:
                return SerialAddress.DataBits.DATABITS_6;
            case SerialPort.DATABITS_7:
                return SerialAddress.DataBits.DATABITS_7;
            case SerialPort.DATABITS_8:
                return SerialAddress.DataBits.DATABITS_8;
        }
        throw new InvalidParameterException("broken dataBits");
    }

    public SerialAddress.StopBits getStopBits() {
        switch (stopBits){
            case SerialPort.STOPBITS_1:
                return SerialAddress.StopBits.BITS_1;
            case SerialPort.STOPBITS_2:
                return SerialAddress.StopBits.BITS_2;
            case SerialPort.STOPBITS_1_5:
                return SerialAddress.StopBits.BITS_1_5;
        }
        throw new InvalidParameterException("broken stopBits");
    }

    public SerialAddress.Parity getParity() {
        switch (parity){
            case SerialPort.PARITY_NONE:
                return SerialAddress.Parity.NONE;
            case SerialPort.PARITY_ODD:
                return SerialAddress.Parity.ODD;
            case SerialPort.PARITY_EVEN:
                return SerialAddress.Parity.EVEN;
            case SerialPort.PARITY_MARK:
                return SerialAddress.Parity.MARK;
            case SerialPort.PARITY_SPACE:
                return SerialAddress.Parity.SPACE;
        }
        throw new InvalidParameterException("broken parity");
    }

    public SerialAddress.FlowControl getFlowControl() {
        switch (flowControl){
            case SerialPort.FLOWCONTROL_NONE:
                return SerialAddress.FlowControl.NONE;
            case SerialPort.FLOWCONTROL_RTSCTS_IN:
                return SerialAddress.FlowControl.RTSCTS_IN;
            case SerialPort.FLOWCONTROL_RTSCTS_OUT:
                return SerialAddress.FlowControl.RTSCTS_OUT;
            case SerialPort.FLOWCONTROL_XONXOFF_IN:
                return SerialAddress.FlowControl.XONXOFF_IN;
            case SerialPort.FLOWCONTROL_XONXOFF_OUT:
                return SerialAddress.FlowControl.XONXOFF_OUT;
        }
        throw new InvalidParameterException("broken flowControl");
    }
}
